package com.kingsoft.dc.khaos.scheduler

/**
  * Created by chengguangqing on 2019/5/27.
  */
class ApplicationWaiter(
                       khaosScheduler: KhaosScheduler,
                       val applicationId:Int,
                       totalJobs:Int)  extends ApplicationListener{

  private var finishedJobs = 0

  @volatile
  private var _applicationFinished = totalJobs == 0

  def applicationFinished: Boolean = _applicationFinished

  private var applicationResult: ApplicationResult = if(applicationFinished) ApplicationSucceeded else null

  def cancel(): Unit = {
    khaosScheduler.cancelApplication(applicationId)
  }

  override def applicationSucceeded(): Unit = synchronized{
    if(_applicationFinished){
      throw new UnsupportedOperationException("jobSucceeded() called on a finished ApplicationWaiter")
    }
    finishedJobs += 1
    if(finishedJobs == totalJobs){
      _applicationFinished = true
      applicationResult = ApplicationSucceeded
      this.notifyAll()
    }
  }

  override def applicationFailed(exception: Exception): Unit = synchronized{
    _applicationFinished = true
    applicationResult = ApplicationFailed(exception)
    this.notifyAll()
  }

  def awaitResult():ApplicationResult = synchronized{
    while(!_applicationFinished){
      this.wait()
    }
    return applicationResult
  }
}
